package com.wjv.example.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.wjv.example.service.PaymentFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * <p>Title: OrderController</p>
 *
 * @author: wjv
 * @Date: Create in 2020/10/13 11:19
 * @Description:
 */
@RestController
public class OrderController {

    @Autowired
    PaymentFeignService paymentFeignService;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${service-url.nacos-user-service}")
    private String url;

    @GetMapping("/hello")
    public String hello () {
        return "hello, word";
    }

    /**
     * 使用 restTemplate 方式调用远程服务
     * 如果 远程服务不可用，会走 SentinelResource配置的 备用方法 fallback
     * @param id
     * @return
     */
    @GetMapping("/getA")
    @SentinelResource(value = "getA", blockHandler = "getBlockHandler", fallback = "getFallBack")
    public String getA (@RequestParam int id) {
        return restTemplate.getForObject(url + "/payment/nacos/"+ id, String.class);
    }

    /**
     * 使用 openFeign 方式调用远程服务
     * 如果 远程服务不可用或者触发sentinel的限制条件，会走 openFeign配置的 备用方法 fallback
     * @param id
     * @return
     */
    @GetMapping("/getB")
    @SentinelResource(value = "getB", blockHandler = "getBlockHandler", fallback = "getFallBack")
    public String getB (@RequestParam int id) {
        return paymentFeignService.getPayment(id);
    }

    /**
     * 一定要加 BlockException exception这个参数
     * @param id
     * @param exception
     * @return
     */
    public String getBlockHandler(int id, BlockException exception) {
        return "请稍后再试, " + id;
    }

    /**
     * 一定要加 Throwable throwable这个参数
     * @param id
     * @param throwable
     * @return
     */
    public String getFallBack(int id, Throwable throwable) {
        return "请求出错，" + id;
    }
}
